package com.easy.lab.shixun.controller;

import com.easy.lab.shixun.api.bo.request.GroupRequest;
import com.easy.lab.shixun.api.bo.response.GroupResponse;
import com.easy.lab.shixun.api.bo.response.TokenInfoResponse;
import com.easy.lab.shixun.api.service.GroupMemberService;
import com.easy.lab.shixun.api.service.LoginService;
import com.easy.lab.shixun.common.base.BaseError;
import com.easy.lab.shixun.common.base.BaseException;
import com.easy.lab.shixun.common.base.BaseResponse;
import com.easy.lab.shixun.common.utils.RequestUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @Author: https://gitee.com/wesleyOne
 * @Date: 12.09 2019
 */
@Api(tags = "群组相关接口")
@RestController
@RequestMapping(value = "/group")
public class GroupController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private GroupMemberService groupMemberService;

    @ApiOperation(value = "加入群接口",notes = "绑定用户与当前群的关系")
    @ApiImplicitParam(name = "guid", value = "群唯一编号", defaultValue = "meetup", required = true)
    @ResponseBody
    @RequestMapping(value = "/join/{guid}", method = { RequestMethod.POST})
    public BaseResponse<GroupResponse> join(@PathVariable(name = "guid")String groupUniqueId, HttpServletRequest request) {
        String token = RequestUtil.getCookievalue(request);
        if ( StringUtils.isNotBlank(token) ) {
            TokenInfoResponse tokenInfoResponse = loginService.checkLogin(token);
            if (Objects.nonNull(tokenInfoResponse) && tokenInfoResponse.getIsLogin()) {
                try {
                    groupMemberService.relateTokenWithGroup(token, groupUniqueId);
                } catch (BaseException e) {
                    return BaseResponse.error(BaseError.UNLOGIN);
                }
                GroupRequest groupRequest = new GroupRequest();
                groupRequest.setGroupUniqueId(groupUniqueId);
                GroupResponse groupResult = groupMemberService.getGroupInfo(groupRequest);
                return new BaseResponse<>(groupResult);
            }
        }
        return BaseResponse.error(BaseError.UNLOGIN);
    }
}
